export interface PlatformInfo {
  ios: boolean;
  android: boolean;

  app: boolean;
  ios_app: boolean;
  android_app: boolean;

  alipay: boolean;
  ios_alipay: boolean;
  android_alipay: boolean;

  wechat: boolean;
  ios_wechat: boolean;
  android_wechat: boolean;

  platform: string;
}

let appIdentifier = 'likit';

export const setAppIdentifier = (newAppIdentifier: string) => {
  appIdentifier = newAppIdentifier;
};

export const getPlatformInfo = (appIdentifierCustom?: string): PlatformInfo => {
  const userAgent = window.navigator.userAgent.toLowerCase();

  const ios = !!userAgent.match(/\(i[^;]+;( u;)? cpu.+mac os x/);
  const android = userAgent.indexOf('android') > -1 || userAgent.indexOf('linux') > -1 || !ios;

  const app = userAgent.indexOf(`${(appIdentifierCustom || appIdentifier).toLowerCase()}/`) > -1;
  const ios_app = ios && app;
  const android_app = android && app;

  const alipay = userAgent.indexOf('alipayclient/') > -1 && !app;
  const ios_alipay = ios && alipay;
  const android_alipay = android && alipay;

  const wechat = userAgent.indexOf('micromessenger/') > -1 && userAgent.indexOf('wxwork/') === -1 && !app;
  const ios_wechat = ios && wechat;
  const android_wechat = android && wechat;

  let platform;
  if (ios_app) {
    platform = 'ios_app';
  } else if (android_app) {
    platform = 'android_app';
  } else if (app) {
    platform = 'app';
  } else if (ios_alipay) {
    platform = 'ios_alipay';
  } else if (android_alipay) {
    platform = 'android_alipay';
  } else if (alipay) {
    platform = 'alipay';
  } else if (ios_wechat) {
    platform = 'ios_wechat';
  } else if (android_wechat) {
    platform = 'android_wechat';
  } else if (wechat) {
    platform = 'wechat';
  } else if (ios) {
    platform = 'ios';
  } else if (android) {
    platform = 'android';
  } else {
    platform = 'web';
  }

  const platformInfo = {
    ios: ios,
    android: android,

    app: app,
    ios_app: ios_app,
    android_app: android_app,

    alipay: alipay,
    ios_alipay: ios_alipay,
    android_alipay: android_alipay,

    wechat: wechat,
    ios_wechat: ios_wechat,
    android_wechat: android_wechat,

    platform: platform,
  };

  return platformInfo;
};
